package com.github.llyb120.yaomq.server;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.github.llyb120.yaomq.server.MQService.*;

@Component
public class RequestHandler implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI();
        check: switch (url){
            case URL_CONNECT:
                break;

            default:
                if(request.getMethod().equalsIgnoreCase("options")){
                    break check;
                }
                //是否需要转发
                try{
                   int code = proxyWithSocket(request, response);
                   switch (code){
                       case CODE_ALL_SUCCESS:
                           break;

                       case CODE_FAILED:
                           break check;

                       case CODE_ONE_SUCCESS:
                           return;
                   }
                } catch (Exception e){
                    e.printStackTrace();
                }
        }
        filterChain.doFilter(servletRequest, servletResponse);
//        servletRequest = new HttpServletRequestWrapper((HttpServletRequest) servletRequest){
//            @Override
//            public String getRequestURI() {
//                return Math.random() > 0.5 ? "/ttt" : "/fff";
////                return super.getRequestURI();
//            }
//        };
//        filterChain.doFilter(servletRequest, servletResponse);
    }


}
